'use strict';


// 查询趣事分享列表
const db = uniCloud.database();
exports.main = async (event, context) => {

	// 查询条件
	let parmse = {};
	
	let res = null;

	if (event.state == 'add') {
		parmse = event
		delete parmse['state'] //删除这个多余的状态
		res = await db.collection('accountBookDetail').add(parmse);
		return {
			code: 200,
			message: "操作成功"
		}
	} else if (event.state == 'update') {
		parmse = event
		let _id = event._id
		delete parmse['state'] //删除这个多余的状态
		delete parmse['_id'] //删除这个多余的状态
		res = await db.collection('accountBookDetail').where({
			_id: _id
		}).update(parmse)
		
		return {
			code: 200,
			message: "操作成功"
		}
	} else if (event.state == 'look') {
		parmse = event
		let cutName = event.cutName ? event.cutName : "天"
		
		delete parmse['cutName']
		delete parmse['state']
		
		if(parmse.createTime){
			parmse.createTime = new RegExp(parmse.createTime, 'g')
		}else{
			delete parmse['createTime']
		}
		
		res = await db.collection('accountBookDetail').where(db.command.or({
			...parmse
		})).orderBy('createTime', 'desc').get() //获取数据
		
		// 计算总和并且合并相同类型的数
		
		
		// 解析 JSON 数组成列表
		const records = res.data
		
		// 合并交易类型相等的记录
		const mergedRecords = {};
		for (const record of records) {
		  const type = record.type;
		  if (type in mergedRecords) {
		    // 将交易金额累加到已有记录上
			mergedRecords[type].money = mergedRecords[type].money * 1
		    mergedRecords[type].money += parseFloat(record.money) * 1;
		  } else {
		    // 创建新的记录
		    mergedRecords[type] = Object.assign({}, record);
		  }
		}
		
		// 转换成 JSON 数组
		const mergedList = Object.values(mergedRecords);

		let sum = 0
		
		mergedList.forEach(item=>{
			sum += item.money * 1
		})
		
		// 计算每一条的百分比
		mergedList.forEach(item=>{
			item.percentage =( (item.money / sum) * 100).toFixed(2)
		})
		
		if(cutName == '天'){
			// 通过百分比排序
			mergedList.sort((a, b) => b.money - a.money );  
		}

		

		
		return {
			code: 200,
			message: "操作成功",
			data: mergedList,
			total:res.affectedDocs,
			sum:sum,
			original:res.data
		}
	}else if(event.state == 'delete'){
		parmse = event
		
		delete parmse['state']
		
		console.log(parmse._id , "parmse._id");
		
		let res = await db.collection('accountBookDetail').doc(parmse._id).remove()
		
		return {
			code: 200,
			message: "操作成功"
		}
	}

}